<template>
    <div class="tougao-middle" style="padding-left:20px;">


        <div style="width:100%;min-height:40px;color:#222222;display:flex;margin-top:20px;">
            <h1>普通投稿</h1>
            <span style="color:#666666;margin-top:10px;">
                <p>（单次最多允许上传1部视频，推荐采用mp4格式，可有效缩短审核转码耗时）</p>
            </span>
        </div>
        <el-upload
            action="#"
            :auto-upload="false"
            accept=".mp4"
            :on-change="beforeFileUpload"
            :limit="1"
            list-type="picture">
            <div style="margin-top:10px;">
                <el-button size="small" type="primary"><i class="el-icon-plus"></i>添加视频</el-button>
            </div>
        </el-upload>

        <el-divider></el-divider>

        <div style="width:100%;min-height:40px;color:#222222;">
            <h1>基本信息</h1>
            <div style="color:#101010;margin-top:20px;">
                <h3><span style="color:red;">*</span>视频封面设置</h3>
                <span style="color:#666666;margin-top:2px;">
                    <p>（格式jpeg、png，文件大小≤5MB）</p>
                </span>
            </div>

            <div style="width:100%;float:left;margin-bottom:20px;">
                <div style="width:25%;float:left;">
                    <el-upload style="margin:20px auto 10px 0"
                               class="avatar-uploader"
                               accept=".jpg,jpeg,.png"
                               action="#"
                               :auto-upload="false"
                               :show-file-list="false"
                               :on-change="function(file, fileList){ return beforeCoverImgUpload(file,1)}"
                    >
                        <img v-if="videoCoverImgUrl220x125" :src="videoCoverImgUrl220x125" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon">
                        </i>

                    </el-upload>
                    <div>(宽度220px,高度125px图片)</div>
                </div>
            </div>

            <div style="color:#101010;margin-top:20px;">
                <h3><span style="color:red;">*</span>视频分区</h3>
                <div style="margin-top:10px;">
                    <el-cascader
                        v-model="chamVideoForm.videoFenqu"
                        :options="options"
                        separator=" → "></el-cascader>
                </div>
            </div>

            <div style="color:#101010;margin-top:20px;">
                <h3>视频分组</h3>
                <div style="margin-top:10px;">
                    <el-radio v-model="isVideoFenzu" label="true">视频分组</el-radio>
                    <el-radio v-model="isVideoFenzu" label="false">视频不分组</el-radio>
                </div>
                <div style="margin-top:10px;" v-show="isVideoFenzu=='true'">
                    <div v-show="videoFenzuOptions==null || videoFenzuOptions.length==0">
                        <span style="color:#FD4C5D;cursor:pointer;padding-left:10px;" @click="doAddPutongFenzu">当前尚未有分组信息，请添加分组信息!</span>
                    </div>

                    <div v-show="videoFenzuOptions!=null && videoFenzuOptions.length>0">
                        <el-select v-model="fenzuId" filterable placeholder="请选择">
                            <el-option
                                v-for="item in videoFenzuOptions"
                                :key="item.fenzuId"
                                :label="item.fenzuName"
                                :value="item.fenzuId">
                            </el-option>
                        </el-select>
                        <span style="color:#FD4C5D;cursor:pointer;padding-left:10px;" @click="doAddPutongFenzu">分组信息中如未有当前视频所属分区，添加分组信息!</span>
                    </div>
                </div>
            </div>

            <div style="color:#101010;margin-top:20px;">
                <h3><span style="color:red;">*</span>视频标题</h3>
                <div style="margin-top:10px;">
                    <el-input v-model="chamVideoForm.videoTitle"/>
                </div>
            </div>

            <div style="color:#101010;margin-top:20px;">
                <h3><span style="color:red;">*</span>视频简介</h3>
                <div style="margin-top:10px;">
                    <el-input
                        type="textarea"
                        :rows="6"
                        v-model="chamVideoForm.videoSummary"
                    >
                    </el-input>
                </div>
            </div>
            <div style="margin-top:20px;margin-bottom:60px;">
                <el-button type="primary" @click="doSubmit" :loading="isTougaoLoading">立即投稿</el-button>
            </div>
        </div>

    </div>
</template>

<script>

    import chamUtils from '@/utils/chamUtils';

    export default {
        name: "putongTougao",
        data(){
            return{
                isTougaoLoading:false,
                isVideoFenzu:'false',
                fenzuId:null,
                options: [{
                    value: '02',
                    label: '电视剧',
                    children: [{
                        value: '01',
                        label: '日剧'
                    }, {
                        value: '02',
                        label: '港剧'
                    }, {
                        value: '03',
                        label: '国产剧'
                    }]
                },{
                    value: '03',
                    label: '电影'
                },{
                    value: '04',
                    label: '音乐',
                    children: [{
                        value: '01',
                        label: '原创音乐'
                    }, {
                        value: '02',
                        label: '翻唱'
                    }, {
                        value: '03',
                        label: 'MV'
                    }]
                },{
                    value: '05',
                    label: '宅舞'
                },{
                    value: '06',
                    label: '综艺'
                },{
                    value: '07',
                    label: 'ASMR'
                },{
                    value: '08',
                    label: '电子歌姬'
                },{
                    value: '09',
                    label: '纪录片'
                },{
                    value: '10',
                    label: '声优'
                }],
                videoFenzuOptions:null,
                videoCoverImgUrl220x125: '',//预览图
                chamVideoForm:{
                    videoCoverImg220x125:null,
                    videoFenqu:'',
                    videoTitle:'',
                    videoSummary:''//视频简介
                },
                videoSection:[],//视频文件切片
                uuidList:[],
                fileName:'',
                videoTimeStr:'00:00:00',

            }
        },
        methods:{
            doAddPutongFenzu(){
                this.$emit('naviIndexChange',6)
            },
            beforeFileUpload(file){
                var self = this;
                file.url =  "http://localhost:8083/cham/img/chaos-video.png";

                //获取视频或者音频时长
                var url = URL.createObjectURL(file.raw);
                var audioElement = new Audio(url);
                //var duration;
                audioElement.addEventListener("loadedmetadata", function(_event) {
                    self.videoTimeStr = chamUtils.getTimeStrFormNum(audioElement.duration);
                });


                self._doFilePiece(file.raw);
            },
            beforeCoverImgUpload(file,index){
                //视频预览图上传前的操作
                var fileRaw = file.raw;
                var self = this;
                var tempVideoCoverImgUrl = URL.createObjectURL(fileRaw);
                if(index===1){
                    self.videoCoverImgUrl220x125 = tempVideoCoverImgUrl;
                    self.chamVideoForm.videoCoverImg220x125 = fileRaw;
                }
            },

            //对要上传的文件进行切片
            _doFilePiece(file){
                //定义切片大小，每个切片大小为2MB
                var bytesPerPiece = 2* 1024 * 1024;
                //定义一个变量用于存储切片数
                var totalPieces;
                //第一步，执行文件切片
                var self = this;
                // var chamVideoForm = self.chamVideoForm;
                var videoFile = file;

                var start = 0;
                var end = 0;
                var index = 0;
                var filesize = videoFile.size;
                var fileName = Date.parse(new Date())+"_"+videoFile.name;
                self.fileName = fileName;
                //计算文件切片总数
                totalPieces = Math.ceil(filesize / bytesPerPiece);
                for(let i=0;i<totalPieces;i++){
                    start = i*bytesPerPiece;
                    end = (i+1)*bytesPerPiece;
                    if(end > filesize) {
                        end = filesize;
                    }
                    var chunk = videoFile.slice(start,end);//切割文件
                    //将切割后的文件放入videoSection中
                    var chunkTempFile = {};
                    chunkTempFile.file = chunk;
                    chunkTempFile.uuid = chamUtils.uuid();
                    self.videoSection.push(chunkTempFile);
                    self.uuidList.push(chunkTempFile.uuid);

                }
            },
            doSubmit(){
                var self = this;
                self.isTougaoLoading = true;
                var fileName = self.fileName;
                var videoSection = self.videoSection;
                //提交视频分片
                for(let i=0;i<videoSection.length;i++){
                    var fileForm = videoSection[i];
                    var formData = new FormData();
                    formData.append("file",fileForm.file);
                    formData.append("uuid",fileForm.uuid);
                    self.$api.post('video-service/tougaoController/videoSection',formData,result=>{
                    });
                }

                //合并分片
                var formData = new FormData();
                formData.append("uuidList",self.uuidList);
                formData.append("fileName",fileName);
                self.$api.post('video-service/tougaoController/mergeVideo',formData,result=>{
                });

                //合并主逻辑
                var chamVideoForm = self.chamVideoForm;
                var videoFenquParent = chamVideoForm.videoFenqu[0];
                var videoFenquChild = chamVideoForm.videoFenqu[1];
                if(videoFenquChild===undefined){
                    videoFenquChild = '00';
                }

                var formData = new FormData();
                formData.append("videoCoverImg220x125",chamVideoForm.videoCoverImg220x125);
                formData.append("fileName",fileName);
                formData.append("fenquParent",videoFenquParent);
                formData.append("fenquChild",videoFenquChild);
                formData.append("videoTitle",chamVideoForm.videoTitle);
                formData.append("videoSummary",chamVideoForm.videoSummary);
                formData.append("videoTimeStr",self.videoTimeStr);

                if(self.isVideoFenzu==='true'){
                    formData.append("fenzuId",self.fenzuId);
                }

                if(self.isVideoFenzu==='false'){
                    formData.append("fenzuId",0);
                }
                this.$api.post('video-service/tougaoController/putongTougao',formData,result=>{
                    self.isTougaoLoading = false;
                    if(result==="TOUGAO_SUCCESS"){
                        self.$notify({
                            title: '投稿成功',
                            message: '投稿成功.',
                            type: 'success',
                            position: 'bottom-right'
                        });
                    }
                });


            }
        },
        mounted() {
            //去后台查询当前用户的个人分组信息
            var self = this;
            self.$api.get('video-service/fenzuController/getFenzuInfoByUUID',null,result=>{
                self.videoFenzuOptions = result;
            });
        }
    }
</script>

<style scoped>
    .tougao-middle{
        border-left: 1px solid #f4f4f4;
        width:999px;
        min-height:500px;
        float:left;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 220px;
        height: 130px;
        line-height: 130px;
        text-align: center;
    }

    .avatar-uploader{
        width:220px;
        height:130px;
        margin-top:20px;
        border-radius: 4px;
        border:1px dashed #cccccc;
    }

    .avatar {
        width: 220px;
        height: 130px;
        display: block;
    }


</style>
